package com.wtgroup.demo.draft;

import java.util.Arrays;

import com.wtgroup.demo.common.judge.Judger;
import com.wtgroup.demo.common.util.RandomUtil;
import com.wtgroup.demo.common.util.Sout;

import cn.hutool.core.util.ArrayUtil;

public class BiSearch {

    public static void main(String[] args) {
        
        Judger.of(() -> {
            int[] arr = RandomUtil.range(RandomUtil.randomInt(0, 50), RandomUtil.randomInt(0, 100));
            // int[] arr = {1,2,3,4};
            int target = 18;
            int res = new BiSearch().biSearch_while(arr, target);
            int refer = ArrayUtil.indexOf(arr, target);
            if (res != refer) {
                Sout.println("res:", res, "refer:", refer);
                Sout.println(arr);
            }

            return res == refer;
        })
        .start().print();

    }


    public int biSearch_while(int[] arr, int target) {
        int lo = 0;
        int hi = arr.length -1;
        int res = -1;
        while (lo <= hi) {
            int mid = (lo + hi) / 2;
            if (target == arr[mid]) {
                res = mid;
                break;
            } else if (target < arr[mid]) {
                hi = mid - 1;
                continue;
            } else if (target > arr[mid]) {
                lo = mid + 1;
                continue;
            }
        }

        return res;
    }
}
